using Microsoft.AspNetCore.Mvc;
using TradeFlow.Server.Language;

namespace TradeFlow.Server.Service;

[ApiExplorerSettings(GroupName = "TradeFlow")]
public partial class JxPartnerService : IApplicationService
{
    /// <summary>
    /// 商业伙伴仓储
    /// </summary>
    private readonly SugarRepository<JxPartner> _partnerRepository;
    private readonly ICurrentUser _currentUser;

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="partnerRepository"></param>
    /// <param name="currentUser"></param>
    public JxPartnerService(SugarRepository<JxPartner> partnerRepository, ICurrentUser currentUser)
    {
        _partnerRepository = partnerRepository;
        _currentUser = currentUser;
    }

    //public Task<PagingResult<PartnerInfo>> QueryPartnersAsync(PagingCriteria criteria)
    //{
    //    return Database.Query<JxPartner>(criteria).ToPageAsync<PartnerInfo>();
    //}

    //public async Task<Result> DeletePartnersAsync(List<PartnerInfo> infos)
    //{
    //    if (infos == null || infos.Count == 0)
    //        return Result.Error(Language.SelectOneAtLeast);

    //    var database = Database;
    //    var oldFiles = new List<string>();
    //    var result = await database.TransactionAsync(Language.Delete, async db =>
    //    {
    //        foreach (var item in infos)
    //        {
    //            await db.DeleteFilesAsync(item.Id, oldFiles);
    //            await db.DeleteAsync<JxPartner>(item.Id);
    //        }
    //    });
    //    if (result.IsValid)
    //        AttachFile.DeleteFiles(oldFiles);
    //    return result;
    //}

    //public async Task<Result> SavePartnerAsync(UploadInfo<PartnerInfo> info)
    //{
    //    var database = Database;
    //    var model = await database.QueryByIdAsync<JxPartner>(info.Model.Id);
    //    model ??= new JxPartner();
    //    model.FillModel(info.Model);

    //    var vr = model.Validate(Context);
    //    if (vr.IsValid)
    //    {
    //        if (await database.ExistsAsync<JxPartner>(d => d.Id != model.Id && d.Name == model.Name))
    //            vr.AddError($"{model.Type}名称已存在！");
    //    }
    //    if (!vr.IsValid)
    //        return vr;

    //    var fileFiles = info.Files?.GetAttachFiles(nameof(JxPartner.Files), "PartnerFiles");
    //    return await database.TransactionAsync(Language.Save, async db =>
    //    {
    //        await db.AddFilesAsync(fileFiles, model.Id, key => model.Files = key);
    //        await db.SaveAsync(model);
    //        info.Model.Id = model.Id;
    //    }, info.Model);
    //}


    /// <summary>
    /// 查询商业伙伴分页列表
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    public async Task<RestfulResult<PageResult<JxPartner>>> GetPagesAsync(JxPartnerPageParam? data)
    {
        var restful = new RestfulResult<PageResult<JxPartner>>() { Code = CodeStatus.OK };
        data ??= new JxPartnerPageParam { PageNo = 1, PageSize = 10 };
        
        var query = _partnerRepository.AsQueryable().Where(u => u.Creator == _currentUser.UserId);
        
        // 添加查询条件
        if (!string.IsNullOrEmpty(data.Type))
            query = query.Where(u => u.Type == data.Type);
        if (!string.IsNullOrEmpty(data.Name))
            query = query.Where(u => u.Name.Contains(data.Name));
        if (!string.IsNullOrEmpty(data.ShortName))
            query = query.Where(u => u.ShortName.Contains(data.ShortName));
        if (!string.IsNullOrEmpty(data.Contact))
            query = query.Where(u => u.Contact.Contains(data.Contact));
        
        var result = await query.ToPageAsync(data.PageNo, data.PageSize);
        restful.Data = result;
        return restful;
    }

    /// <summary>
    /// 获取所有商业伙伴列表
    /// </summary>
    /// <returns></returns>
    public async Task<RestfulResult<PageResult<JxPartner>>> GetListAsync()
    {
        var restful = new RestfulResult<PageResult<JxPartner>>() { Code = CodeStatus.OK };
        PageParam data = new PageParam { PageNo = 1, PageSize = 1000 };
        
        var query = await _partnerRepository.AsQueryable()
            .Where(u => u.Creator == _currentUser.UserId)
            .OrderByDescending(u => u.Id)
            .ToPageAsync(data.PageNo, data.PageSize);
        
        restful.Data = query;
        return restful;
    }

    /// <summary>
    /// 添加商业伙伴
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    [UnitOfWork]
    public async Task<RestfulResult> AddAsync(JxPartner data)
    {
        RestfulResult restful = new() { Code = CodeStatus.BadRequest };
        
        // 检查名称是否重复
        var isExist = await _partnerRepository.IsAnyAsync(u => u.Name == data.Name && u.Creator == _currentUser.UserId);
        if (isExist)
        {
            restful.Message = i18n.data_duplicate;
            return restful;
        }
        
        data.Creator = _currentUser.UserId;
        bool result = await _partnerRepository.InsertAsync(data);
        if (result)
        {
            restful.Data = result;
            restful.Code = CodeStatus.OK;
            return restful;
        }
        else
        {
            restful.Message = $"{i18n.add}{i18n.fail}";
            return restful;
        }
    }

    /// <summary>
    /// 更新商业伙伴
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    public async Task<RestfulResult> UpdateAsync(JxPartner data)
    {
        RestfulResult restful = new() { Code = CodeStatus.BadRequest };
        
        var partner = await _partnerRepository.GetByIdAsync(data.Id);
        if (partner == null || partner.Creator != _currentUser.UserId)
        {
            restful.Message = $"{i18n.not_exist}";
            return restful;
        }
        
        // 检查名称是否重复（排除当前记录）
        var isExist = await _partnerRepository.IsAnyAsync(u => u.Name == data.Name && u.Id != data.Id && u.Creator == _currentUser.UserId);
        if (isExist)
        {
            restful.Message = i18n.data_duplicate;
            return restful;
        }
        
        bool result = await _partnerRepository.UpdateAsync(data, true, true, $"{i18n.modify}");
        if (result)
        {
            restful.Data = result;
            restful.Code = CodeStatus.OK;
            return restful;
        }
        else
        {
            restful.Message = $"{i18n.modify}{i18n.fail}";
            return restful;
        }
    }

    /// <summary>
    /// 删除商业伙伴
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    public async Task<RestfulResult> DeleteAsync([FromBody] EntityBaseId data)
    {
        RestfulResult restful = new() { Code = CodeStatus.BadRequest };
        
        if (data.Id == 0)
        {
            restful.Message = $"{i18n.delete}{i18n.fail}";
            return restful;
        }
        
        // 检查是否存在且属于当前用户
        var partner = await _partnerRepository.GetByIdAsync(data.Id);
        if (partner == null || partner.Creator != _currentUser.UserId)
        {
            restful.Message = $"{i18n.not_exist}";
            return restful;
        }
        
        bool isDelete = await _partnerRepository.DeleteByIdAsync(data.Id);
        if (isDelete)
        {
            restful.Data = isDelete;
            restful.Message = $"{i18n.delete}{i18n.success}";
            restful.Code = CodeStatus.OK;
            return restful;
        }
        else
        {
            restful.Data = isDelete;
            restful.Message = $"{i18n.delete}{i18n.fail}";
            return restful;
        }
    }
}